package cn.sinjet.model.carsystem;

import com.mgroup.wazehelper.R;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.entity.UpgradeInfo;
import cn.sinjet.model.carassist.AppModel;
import cn.sinjet.utils.ShowDialogUtil;
import cn.sinjet.utils.ShowDialogUtil.OnDialogAction;
import cn.sinjet.utils.ToastUtil;
import cn.sinjet.utils.UpgradeUtil;
import cn.sinjet.viewmodel.IOnViewEventListener;
import cn.sinjet.viewmodel.ViewEvent;
import cn.sinjet.viewmodel.ViewModel;


public class CarModel implements IOnViewEventListener{
	private static String tag = "Dispatcher";
	WorkerThread workerThread = null;
	ModelMsgHandler modelMsgHandler = null;
	private boolean isFirstEnter = true;
	private static CarModel carModel = null;
	
	public DeviceModule devModule = new DeviceModule(this);
	public TpmsModule tpmsModule = new TpmsModule(this);
	public ControlModule controlModule = new ControlModule(this);
	public RadarModule radarModule = new RadarModule(this);
	
	public CarModel(){
		workerThread = new WorkerThread("Model Main ProcThread");
		modelMsgHandler = new ModelMsgHandler(this,workerThread.getLooper());
		ViewModel.getIns().setOnViewEventListener(this);
	}
	
	public  static CarModel getInstance(){
 	   if(carModel == null)
 		  carModel = new CarModel();
 	   return carModel;
    }
	
	public ModelMsgHandler getMsgHandler(){
		 return modelMsgHandler; 
	}
	
	
	public void onAppStartup(){
		  //auto login
//	     ModelMsgHandler msgHandler = model.getMsgHandler();
	     Message msg = modelMsgHandler.obtainMessage();
	     msg.what = ModelMsgHandler.MSG_FROM_APP;
	     modelMsgHandler.sendMessage(msg);
	}	

	/*public void setContext(Context context,int pageFlag){
		this.context = context;
		ViewModel.getIns().setCurContext(context,pageFlag);
	}*/
	UIHandler mUIHandler = new UIHandler();
	
	@SuppressLint("HandlerLeak") class UIHandler extends Handler{
		@SuppressLint("ShowToast") @Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 1:
				   Log.d("uithread", "handle msg");
			       Bundle bundle = msg.getData();
			       String content = bundle.getString("CONTENT");
			       String title = bundle.getString("TITLE");
			       String positiveText  = bundle.getString("POSITIVE");
			       String negativeText = bundle.getString("NEGATIVE");
//			       showUpgradeAlert(content);
			       showDialogAlert(title, content, negativeText, positiveText);
				break;
			case 2:
				  bundle = msg.getData();
			      content = bundle.getString("CONTENT");
			      if(ViewModel.getIns().getCurContext() != null){
			    	  Log.d("uithread","showToest:"+content);
// 			          Toast.makeText(ViewModel.getIns().getCurContext(),content, Toast.LENGTH_SHORT).show();
 			          ToastUtil.showToast(ViewModel.getIns().getCurContext(),content);
			      }
				break;
			}
		}
	}
	String apkUrl = null;
	public void startVersionCheck(final boolean showSuccee) {
		// TODO Auto-generated method stub
		Log.i(tag, "startVersionCheck");
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
			       UpgradeUtil upgrader = new UpgradeUtil(SinjetApplication.getInstance());
			       String url = "http://120.24.64.247:8080/sinjetweb/AutoUpgrade?flag=hudhelper";
			       int result = upgrader.haveNewVersion(url);
			       if(result == 1){
			    	   UpgradeInfo upgradeInfo = upgrader.getUpgradeInfo();
			    	   if(upgradeInfo == null)
			    		   return;
			    	   apkUrl = upgradeInfo.downloadUrl;
//			    	   ViewModel.getIns().showAlertInUIThread();
			    	   String strContent = 
			    			       "Version:"+upgradeInfo.vname+"\r\n"
			    			    + "Date:"+upgradeInfo.date+"\r\n"
				    	   		+ "Update Content:\r\n"
				    	   		+ upgradeInfo.updateContent;
//			    	   Message message = Message.obtain(mUIHandler);
//			    	   message.what = 1;
//			    	   Bundle bundle = new Bundle();
//			   		   bundle.putString("CONTENT", strContent);
//			   		   message.setData(bundle);
//			   		   mUIHandler.sendMessage(message);
			    	   showUpgradeDialog(strContent);
			    	   
			       }else if(result == 2){//
			    	   if(showSuccee)
			           showToastInUIThread("It is the latest version");    	   
			       }else{//
			    	   if(showSuccee)
			    	   showToastInUIThread("Version check failed");
			       }
			}
		}).start();
	}
	
	
	public void showUpgradeDialog(String content){
		Log.d("dialog", "showUpgradeDialog");
		ShowDialogUtil dialogUtil = new ShowDialogUtil();
		dialogUtil.setButtonText("update", "later");
		dialogUtil.setOnDialogActionListern(new OnDialogAction() {
			
			@Override
			public void onPositive() {
				// TODO Auto-generated method stub
				Log.d("dialog", "onPositive");
				startUpgrade();
			}
			
			@Override
			public void onNegative() {
				// TODO Auto-generated method stub
				Log.d("dialog", "onNegative");
			}
		});
		dialogUtil.showDialog("New version available", content);
		
	}

	
	public void showDialogAlertInUIThread(String title,String content,String negativeText,String positiveText){
		   Message message = Message.obtain(mUIHandler);
	 	   message.what = 1;
	 	   Bundle bundle = new Bundle();
		   bundle.putString("CONTENT", content);
		   bundle.putString("TITLE", title);
		   bundle.putString("POSITIVE", positiveText);
		   bundle.putString("NEGATIVE", negativeText);
		   message.setData(bundle);
		   mUIHandler.sendMessage(message);
	}
	
	public void showToastInUIThread(String strContent){
		Message message = Message.obtain(mUIHandler);
 	   message.what = 2;
 	   Bundle bundle = new Bundle();
		   bundle.putString("CONTENT", strContent);
		   message.setData(bundle);
		   mUIHandler.sendMessage(message);
	}
	
	private void showDialogAlert(String title,String content,String negativeText,String positiveText){
		Context context = ViewModel.getIns().getCurContext();
		if(context == null)
			return;
		AlertDialog.Builder builer = new Builder(context) ;   
		builer.setTitle(title);  
		builer.setMessage(content);
		  //当点确定按钮时从服务器上下载 新的apk 然后安装   
		builer.setPositiveButton(positiveText, new OnClickListener() {  
		public void onClick(DialogInterface dialog, int which) {
			       if(mOnDialogAction != null) mOnDialogAction.onPositive();
		        }     
	    });  
		    //当点取消按钮时进行登陆
	    builer.setNegativeButton(negativeText, new OnClickListener() {  
	        public void onClick(DialogInterface dialog, int which) {  
	            // TODO Auto-generated method stub
	        	  if(mOnDialogAction != null) mOnDialogAction.onNegative();
	              dialog.dismiss();
	        }  
	    });  
	    AlertDialog dialog = builer.create();  
	    dialog.show();
	}
	
	private void showUpgradeAlert(String content){
		Context context = ViewModel.getIns().getCurContext();
		if(context == null)
			return;
		AlertDialog.Builder builer = new Builder(context) ;   
		builer.setTitle("有新的版本哦");  
		builer.setMessage(content);
		  //当点确定按钮时从服务器上下载 新的apk 然后安装   
		builer.setPositiveButton("马上更新", new OnClickListener() {  
		public void onClick(DialogInterface dialog, int which) {  
		          Log.i("upgrade","下载apk,更新");
		          startUpgrade();
		        }     
	    });  
		    //当点取消按钮时进行登陆
	    builer.setNegativeButton("以后再说", new OnClickListener() {  
	        public void onClick(DialogInterface dialog, int which) {  
	            // TODO Auto-generated method stub  
	              dialog.dismiss();
	        }  
	    });  
	    AlertDialog dialog = builer.create();  
	    dialog.show();
	}
	
	OnDialogAction mOnDialogAction = null;
	public void setOnDialogActionListener(OnDialogAction onDialogAction){
		this.mOnDialogAction = onDialogAction;
	}
	
	public void startUpgrade(){
	    if(apkUrl == null || apkUrl.equals(""))
	    	return;
	    final UpgradeUtil upgradeUtil = new UpgradeUtil(SinjetApplication.getInstance());
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("upgrade", "update thread run");
				try{
						int ret = upgradeUtil.downloadNewApk(apkUrl);
						if(ret == 0){
							Thread.sleep(2000);
							upgradeUtil.installApk();
						}else if(ret == 1){
							CarModel.getInstance().showToastInUIThread("没有外置存储卡，无法下载");
						}else if(ret == -1){
							CarModel.getInstance().showToastInUIThread("下载出错");
						}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	public void onViewEvent(ViewEvent viewEvent) {
		// TODO Auto-generated method stub
		Log.i(tag, "MainModel onViewEvent "+viewEvent.getTag());
		switch(viewEvent.getTag()){
		case R.id.car_window_close:
		case R.id.car_window_open:
		case R.id.car_lock:
		case R.id.car_unlock:
		case R.id.car_trunk_open:
		case R.id.car_power_off:
		case R.id.car_power_on:
		case R.id.car_skylight_open:
		case R.layout.layout_password_dialog:
		case R.id.reset_control_psw:
		case R.id.setting_hud:
		case R.id.setting_hud_screen:
		case R.id.hud_set_back:
		case R.id.hud_set_screen_down:
		case R.id.hud_set_screen_up:
		case R.id.gesture_down:
		case R.id.gesture_up:
		case R.id.gesture_ok:
		case R.id.hud_set_inc:
		case R.id.hud_set_dec:
		case R.id.hud_set_ok:
			controlModule.onViewEvent(viewEvent);
			break;
			
		case R.id.radar_back:
		case R.id.radar_test:
			radarModule.onViewClk(viewEvent);
			break;
			
		case R.id.gear_d_lock_onoff:
		case R.id.gear_p_unlock_onoff:
		
			devModule.onViewEvent(viewEvent);
			break;
			
		case R.id.tpms_enter_pair:
		case R.id.tpms_lf_pair:
		case R.id.tpms_rf_pair:
		case R.id.tpms_lr_pair:
		case R.id.tpms_rr_pair:
		case R.id.car_meter_tpms_tab:
			tpmsModule.onViewClk(viewEvent.getTag());
			break;
		default:
			AppModel.getInstance().onClkView(viewEvent.getTag());
			break;
		}
	}

	
	public boolean isFirstEnter() {
		return isFirstEnter;
	}

	public void setFirstEnter(boolean isFirstEnter) {
		this.isFirstEnter = isFirstEnter;
	}
	
	
	// 消息
	private int mMsgEndPos = 0;
	private int mMsgLen = 0;
	public static final int MCU_MSG_LENGTH = 1024;
	public byte[] mMsgBuf = new byte[MCU_MSG_LENGTH];
	
	public void onRecvMsgFromDevice(byte[] buf,int len){
//		final StringBuilder stringBuilder = new StringBuilder(buf.length);
//		for (byte byteChar : buf)
//			stringBuilder.append(String.format("%02X ", byteChar));
//		Log.i("BT","recvMessage: "+ stringBuilder.toString());

//
//	
        if(len ==0 || buf == null) return;
		int i = 0;
		for (i = 0; i < len; i++) {
			if (mMsgEndPos >= MCU_MSG_LENGTH)
				mMsgEndPos = 0;

			mMsgBuf[mMsgEndPos] = buf[i];
			mMsgEndPos++;
			switch (mMsgEndPos) {
			case 1:
				if ((mMsgBuf[0] & 0xFF) != 0xFF)
					mMsgEndPos = 0;
				break;
			case 2:
				if ((mMsgBuf[1] & 0xFF) != 0x55)
					mMsgEndPos = 0;
				break;
			case 3: {
				mMsgLen = (mMsgBuf[2] & 0xFF);
				if (mMsgLen > 128)
					System.out.println("analyseCarInfo if (m_nDataPacketLen > 128)");
			}
				break;
			default:
				if (mMsgEndPos == 4 + mMsgLen) {
					int j = 0;
					int checkSum = 0;
					for (j = 2; j < mMsgEndPos - 1; j++) {
						checkSum = checkSum + (mMsgBuf[j] & 0xFF);
					}
					if ((checkSum & 0xFF) == (mMsgBuf[mMsgEndPos - 1] & 0xFF)) {
						byte[] carData = new byte[mMsgLen];
						System.arraycopy(mMsgBuf, 3, carData, 0,mMsgLen);
						getOnePackageMsg(carData, mMsgLen);
					}

					mMsgLen = 0;
					mMsgEndPos = 0;
				}
				break;
			}
		}
	}
	
	
    private void getOnePackageMsg(byte[] msg,int len){
    	Message msgBuf = getMsgHandler().obtainMessage();
		msgBuf.what = ModelMsgHandler.MSG_FROM_DEVICE;
		Bundle bundle = new Bundle();
		bundle.putByteArray(ModelMsgHandler.KEY_MSG_DEVICE, msg);
		msgBuf.setData(bundle);
		getMsgHandler().sendMessage(msgBuf); 
    }    
    
    public void onAppMessage(byte[] msg){
    	Message msgBuf = getMsgHandler().obtainMessage();
		msgBuf.what = ModelMsgHandler.MSG_FROM_APP;
		Bundle bundle = new Bundle();
		bundle.putByteArray(ModelMsgHandler.KEY_MSG_APP, msg);
		msgBuf.setData(bundle);
		CarModel.getInstance().getMsgHandler().sendMessage(msgBuf);
    }

	public void init(Context context) {
		// TODO Auto-generated method stub
		controlModule.init(context);
	}
      
	public void deInit() {
		// TODO Auto-generated method stub
		
	}     
    
}
